<template>
  <entity-view
    :operator-type="operatorType"
    :model="beanInfo"
    @submit="submit"
    :rules="rules"
    ref="form"
  >
    <form-item
      label="商圈编号"
      v-model="beanInfo.tradeAreaCode"
      prop="tradeAreaCode"
      disabled
    ></form-item>
    <form-item
      label="商圈名称"
      v-model="beanInfo.tradeAreaName"
      prop="tradeAreaName"
    ></form-item>
    <form-item
      label="商圈描述"
      v-model="beanInfo.tradeAreaDesc"
      prop="tradeAreaDesc"
    ></form-item>
    <form-item
      label="所属机构"
      input-type="select"
      v-model="beanInfo.belongInstId"
      prop="belongInstId"
      :options="belongInstIdList"
      @change="(value) => handleChange(value, 'belongInstId')"
    ></form-item>
    <form-item
      label="所属地区"
      input-type="select"
      v-model="beanInfo.belongAreaCode"
      prop="belongAreaCode"
      :options="belongAreaCodeList"
      allowClear="true"
      :showSearch="true"
      @change="(value) => handleChange(value, 'belongAreaCode')"
      @search="getBelongAreaList"
    ></form-item>
    <form-item
      label="经营范围"
      input-type="select"
      v-model="beanInfo.managementScope"
      prop="managementScope"
      show-search
      :options="managementScopeList"
      @change="(value) => handleChange(value, 'managementScope')"
    ></form-item>
    <form-item
      label="注销原因"
      v-model="beanInfo.cancelReason"
      prop="cancelReason"
      row="3"
      inputType="textarea"
      :disabled="operatorType === 'view'"
      :valid="operatorType==='cancel'"
      v-if="this.operatorType === 'cancel'|| (this.operatorType === 'view' && this.beanInfo.auditStatus === '12')"
    ></form-item>
    <form-item
      label="审批意见"
      v-model="beanInfo.auditRefuseReason"
      prop="auditRefuseReason"
      inputType="textarea"
      v-if="operatorType === 'view' && auditStatus === '13'"
      row="3"
    ></form-item>
  </entity-view>
</template>
<script>
import EntityView from "../../../../components/common/entityView/EntityView.vue";
import FormItem from "../../../../components/common/entityView/FormItem.vue";

export default {
  name: "TradeAreaOperation",
  components: {
    EntityView,
    FormItem,
  },
  props: {
    query: Object,
  },
  data: function () {

    return {
      operatorType: "add",
      loading: false,
      instId:"",
      modalTitle: "",
      modalVisible: true,
      beanInfo: {
        instId: "",
        tradeAreaCode: "",
        tradeAreaName: "",
        tradeAreaDesc: "",
        belongInstId: "",
        belongInstName: "",
        belongAreaCode: "",
        belongAreaName: "",
        managementScope: "",
        cancelReason: "",
        auditRefuseReason: "",
      },
      dataZ: [],//总数据（不会改变）
      sourceOwnerSystems: [],
      valueData: '',
      scrollPage: 1,
      rules: {
        tradeAreaCode: [
          { required: true, message: "请输入商圈编号", trigger: "blur" },
        ],
        tradeAreaName: [
          { required: true, message: "请输入商圈名称", trigger: "blur"  , pattern:"^[a-zA-Z0-9_\u4e00-\u9fa5]+$"},
        ],
        tradeAreaDesc: [
          { required: true, message: "请输入商圈描述", trigger: "blur"  , pattern:"^[a-zA-Z0-9_\u4e00-\u9fa5]+$"},
        ],
        belongInstId: [
          { required: true, message: "请选择所属机构", trigger: "blur" },
        ],
        cancelReason: [
          { required: true, message: "请输入注销原因", trigger: "blur" },
        ],
      },
      belongInstIdList: [],
      belongAreaCodeList: [],
      managementScopeList: [],
      dataZ: [],//总数据（不会改变）
      frontDataZ: [], //存放前100的数据
      valueData: '',
      treePageSize:100
    };
  },
  methods: {
    handleChange(value,param) {
      this.beanInfo[param] = value;
      if(param === 'belongAreaCode'){
        var obj = this.belongAreaCodeList.find(function (obj) {
          return obj.id === value;
        });
        this.beanInfo.belongAreaName = obj.name.split(" - ")[1];
      }
      if(param === 'belongInstId'){
        var obj = this.belongInstIdList.find(function (obj) {
          return obj.id === value;
        });
        this.beanInfo.belongInstName = obj.name;
      }
    },
    async submit() {
      let res;
      switch (this.operatorType) {
        case "add":
          res = await this.add();
          break;
        case "edit":
          res = await this.edit();
          break;
        case "view":
          res = true;
          break;
        case "cancel":
          res = await this.cancel();
          break;
        default:
          break;
      }
      return res;
    },
    async add() {
      try {
        const res = await this.$refs.form.validate();
        if (res) {
          const params = {
            ...this.beanInfo,
            optFlag:"add"
          };
          const res = await this.$post("/admin/merParam/tradeAreaInfo/edit", params);
            if (res.data.code!='100000'){
              this.$message.error(res.data.message);
              return false;
            }else {
              this.$message.success("新增成功！");
              return true;
            }
        }
      } catch (e) {
        console.error(e);
      }
    },
    async edit() {
      const res = await this.$refs.form.validate();
      if (res) {
        const params = {
          ...this.beanInfo,
          optFlag:"upd"
        };
        const res = await this.$post(
          "/admin/merParam/tradeAreaInfo/edit",
          params
        );
        if (res.data.code!='100000'){
          this.$message.error(res.data.message);
          return false;
        }else {
          this.$message.success("修改成功！");
          return true;
        }
      }
    },
    async cancel() {
      const res = await this.$refs.form.validate();
      if (res) {
        const params = {
          id: this.beanInfo.id,
          ...this.beanInfo,
          optFlag: "cancel",
        };
        const res = await this.$post("/admin/merParam/tradeAreaInfo/edit", params);
        if (res.status === 200) {
          this.$message.success("保存成功！");
          return true;
        } else {
          this.$message.error(res.data.message);
          return false;
        }
      }
    },
    resetFields() {
      return this.$refs.form && this.$refs.form.resetFields();
    },
    setOperatorType(type) {
      this.operatorType = type;
    },
    async setBeanInfo({...beanInfo},instId) {
      this.beanInfo = beanInfo;
      this.instId = instId;
      await this.getInstIdOrganizationList();
      await this.getManagementScopeList();
      await this.getBelongAreaList();
      if(this.operatorType === 'add'){
        await this.getEditList()
        return
      }
     // await this.getOne();
    },
    async getOne() {
      try {
        const res = await this.$get("/admin/merParam/tradeAreaInfo/edit", {
          id: this.beanInfo.id,
          optFlag:"detail",
        });
        this.beanInfo = res.data.entity || {};

      } catch (e) {
        console.error(e);
      }
    },
    async getEditList() {
      try {
        const res = await this.$get("/admin/merParam/tradeAreaInfo/edit", {
          optFlag: "add",
          instId: this.instId,
        });
        if (res.status === 200) {
          // debugger
          this.beanInfo = res.data.entity || {};
        }
      } catch (e) {
        console.error(e);
      }
    },
    async getInstIdOrganizationList() {
      try {
        const res = await this.$get("/admin/merParam/UpmpOrganization/instIdOrganizationSelect2List", {
          q: encodeURIComponent(`&${this.instId}`)
        });
        if (res.status === 200) {
          this.belongInstIdList = res.data.results.map(i => {
            i.value = i.id
            return i
          })
        }
      } catch (e) {
        console.error(e);
      }
    },
    async getManagementScopeList() {
      try {
        const res = await this.$get("/admin/mcmp/bMchntBaseInfo/unionMerGrpSelect2List", {
          q: encodeURIComponent(`&${this.instId}`)
        });
        if (res.status === 200) {
          this.managementScopeList = res.data.rows.map(i => {
            i.name = i.grpNo + ' - ' + i.grpDesc
            i.value = i.grpNo
            return i
          })
        }
      } catch (e) {
        console.error(e);
      }
    },
    //通过接口获取数据
    async getBelongAreaList (value = '') {
      var param = {
        q: encodeURIComponent(value + '&${this.instId}'),
          pageSize:100
        }
      this.$get("/admin/merParam/tradeAreaInfo/unionAreaSelect2List", param).then(res => {
        if (res && res.data) {
          this.belongAreaCodeList = res.data.results.map(i => {
            i.name = i.id + ' - ' + i.name
            i.value = i.id
            return i
          })
        }
      }).catch(e => {
        this.$message.error('查询维护信息失败：' + e)
      })
    },

  },
};
</script>

<style scoped>
</style>
